﻿var tenantCode = "000";

var map;
var mapload = false;

$(window).load(function () {
    $(".loading").fadeOut()
})

$(document).ready(function () {
    var whei = $(window).width()
    $("html").css({
        fontSize: whei / 20
    })
    $(window).resize(function () {
        var whei = $(window).width()
        $("html").css({
            fontSize: whei / 20
        })
    });
});

$(document).ready(function () {
    var html = $(".wrap ul").html()
    $(".wrap ul").append(html)
    var ls = $(".wrap li").length / 2 + 1
    i = 0
    ref = setInterval(function () {
        i++
        if (i == ls) {
            i = 1
            $(".wrap ul").css({
                marginTop: 0
            })
            $(".wrap ul").animate({
                marginTop: -'.52' * i + 'rem'
            }, 1000)
        }
        $(".wrap ul").animate({
            marginTop: -'.52' * i + 'rem'
        }, 1000)


    }, 2400);

    var html2 = $(".adduser ul").html()
    $(".adduser ul").append(html2)
    var ls2 = $(".adduser li").length / 2 + 1
    a = 0
    ref = setInterval(function () {
        a++
        if (a == ls2) {
            a = 1
            $(".adduser ul").css({
                marginTop: 0
            })
            $(".adduser ul").animate({
                marginTop: -'.5' * a + 'rem'
            }, 800)
        }
        $(".adduser ul").animate({
            marginTop: -'.5' * a + 'rem'
        }, 800)


    }, 4300);

    initMap();
    // initMapData();
})

function getRoot() {
    var hostName = window.location.hostname;
    var pathName = window.location.pathname;
    var contextPath = pathName.split("/")[1];
    var port = location.port;
    var protocol = location.protocol;

    return protocol + "//" + hostName + ":" + port + "/" + contextPath;

}

function initMapData() {

}



function initMap() {
    // 1 创建Earth的vue组件
    var EarthComp = {

        template: `
                <div style="width: 100%; height: 100%">
                    <div ref="earthContainer" id="earthContainer" style="width: 100%; height: 100%">
                    </div>

                    <div  style="position: absolute; left: 18px; top: 18px">
                        
                    </div>
                    
              
                    <div  class = "floor-control">
                       
                    </div>
                    

                   
                </div>
            `,
        data() {
            return {
                message: '页面加载于 ' + new Date().toLocaleString(),
                _earth: undefined, // 注意：Earth和Cesium的相关变量放在vue中，必须使用下划线作为前缀！
                _bgImagery: undefined,
            };
        },

        // 1.1 资源创建
        mounted() {
            // 1.1.1 初始化地球
            // var earth = new XE.Earth(this.$refs.earthContainer);
            var earth = new XE.Earth("earthContainer");

            // 1.1.2 初始化地图数据
            var map3d = new Map3D(earth, {

            });

            // 通过earth.czm.viewer获得viewer
            var viewer = earth.czm.viewer;


            viewer.scene.light = new Cesium.DirectionalLight({
                direction: new Cesium.Cartesian3(0.354925, -0.890918, -0.283358)
            })



            // 地图数据 json格式，保存在后台，
            var mapData = {

                "dataUrl": "http://124.223.23.99:9000/",

                "cameraViewManager": {
                    "lastView": {
                        "position": [
                            2.0991896557409806,
                            0.5311680680589207,
                            1365.3060606244408
                        ],
                        "rotation": [
                            6.026701586383388,
                            -0.6558441281983081,
                            6.282246002137672
                        ],
                        "fov": 1.0471975511965976,
                        "near": 0.1,
                        "far": 10000000000
                    }
                },
                "floorControlOption": {
                    "floorControlVisible": true,
                    "floorControlPosition": "top-right",
                    "showAllFloorButton": true,
                    "defaultFloorSpace": 10,
                },
                "buildings": [

                ],

                "imageryData": [
                    {
                        "czmObject": {
                            "name": "天地图-影像",
                            "xbsjType": "Imagery",
                            "xbsjImageryProvider": {
                                "XbsjImageryProvider": {
                                    "url": "//t6.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=189b1925501a5ece0893939e50df0304"
                                },
                            }
                        }
                    },
                    {
                        "czmObject": {
                            "name": "天地图-标记",
                            "xbsjType": "Imagery",
                            "xbsjImageryProvider": {
                                "XbsjImageryProvider": {
                                    "url": "//t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=189b1925501a5ece0893939e50df0304"
                                },
                            },
                            xbsjZIndex: 99
                        }
                    }

                ],

                "modelData": [
                    {
                        "ref": "base_tileset",
                        "czmObject": {
                            "name": "三维瓦片数据",
                            "xbsjType": "Tileset",
                            "url": "/tileset.json",
                            // "maximumScreenSpaceError": 17.148375400580687,
                            "xbsjPosition": [
                                1.9627336570437421,
                                0.6600100345534725,
                                -876
                            ],
                            "xbsjUseOriginTransform": false,
                            "xbsjClippingPlanes": {},
                            "xbsjCustomShader": {}
                        }
                    }





                ]


            }


            //设置模型url加载及格式校验正确后的回调函数，注意不是模型加载完成的，模型是异步加载的
            map3d.setTilesetReadyPromiseEvent(function () {
                // alert("TilesetReadyPromise");   


            });

            //设置楼层切换控件的回调函数，e为floor的id
            map3d.setFloorChangedEvent(function (floorId) {
                // alert(floorId);
            });

            //从后台请求返回，调用map3D.openMap()接口
            map3d.openMap(mapData);



            var baseTileset = earth.sceneTree.$refs['base_tileset'].czmObject;

            if (baseTileset) {
                // 拾取事件定制
                baseTileset.onclick = pickedObject => {
                    return false;
                };

                baseTileset.onclickout = () => {

                    return false;
                }

                baseTileset.onmouseover = pickedObject => {
                    return false;
                };
            }


            viewer.scene.globe.depthTestAgainstTerrain = true;


            //逆时针方向采集
            var points = [
                Cesium.Cartesian3.fromDegrees(120.262973, 30.451385),
                Cesium.Cartesian3.fromDegrees(120.265102, 30.448139),
                Cesium.Cartesian3.fromDegrees(120.273177, 30.449709),
                Cesium.Cartesian3.fromDegrees(120.271073, 30.453826),
            ];

            var pointsLength = points.length;

            var clippingPlanes = [];
            for (var i = 0; i < pointsLength; ++i) {
                var nextIndex = (i + 1) % pointsLength;
                var midpoint = Cesium.Cartesian3.add(
                    points[i], points[nextIndex],
                    new Cesium.Cartesian3()
                );

                midpoint = Cesium.Cartesian3.multiplyByScalar(midpoint, 0.5, midpoint);
                var up = Cesium.Cartesian3.normalize(midpoint, new Cesium.Cartesian3());

                var right = Cesium.Cartesian3.subtract(
                    points[nextIndex],
                    midpoint,
                    new Cesium.Cartesian3()
                );
                right = Cesium.Cartesian3.normalize(right, right);

                var normal = Cesium.Cartesian3.cross(
                    right, up, new Cesium.Cartesian3()
                );
                normal = Cesium.Cartesian3.normalize(normal, normal);

                var originCenteredPlane = new Cesium.Plane(normal, 0.0);

                var distance = Cesium.Plane.getPointDistance(
                    originCenteredPlane,
                    midpoint
                );

                clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));

            };


            viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection(
                {
                    planes: clippingPlanes,
                    edgeWidth: 1,//边缘宽度
                    edgeColor: Cesium.Color.RED
                }
            )


            viewer.entities.add({
                id: Math.random().toString(),
                polylineVolume: {
                    positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                        120.265858,
                        30.452674,
                        -20,
                        120.268439,
                        30.448236,
                        -20
                    ]),
                    shape: computeCircle(5.0),
                    material: Cesium.Color.BLUE,
                },
            });


            viewer.entities.add({
                id: Math.random().toString(),
                polylineVolume: {
                    positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                        120.263911,
                        30.449807,
                        -60,
                        120.272285,
                        30.451813,
                        -60
                    ]),
                    shape: computeCircle(10.0),
                    material: Cesium.Color.RED,
                },
            });




        },
        // 1.2 资源销毁
        beforeDestroy() {
            // vue程序销毁时，需要清理相关资源
            this._earth = this._earth && this._earth.destroy();
        },
    }

    // 2 创建vue程序
    // XE.ready()用来加载Cesium.js等相关资源
    XE.ready().then(() => {
        var app = new Vue({
            el: '#vueApp',
            components: {
                EarthComp
            },
        });


        //这个是地球加载后的回调函数
    });
}

function computeCircle(radius) {
    const positions = [];
    for (let i = 0; i < 360; i++) {
        const radians = Cesium.Math.toRadians(i);
        positions.push(
            new Cesium.Cartesian2(
                radius * Math.cos(radians),
                radius * Math.sin(radians)
            )
        );
    }
    return positions;
}


//绑定楼层切换事件
function floorChanged(floor) {
    for (var key in cardMarkerCache) {
        if (typeof cardMarkerCache[key] != "function") {
            var marker = cardMarkerCache[key];
            var _floor = marker._element.getAttribute("_floor");
            if (_floor != floor) {
                marker.remove();
                cardMarkerCache.Remove(key);
            }
        }
    }
}

var currentMarkers = [];

function addWarningData(warningData) {
    if (!warningData) {
        return;
    }
    if (!mapload) {
        return;
    }

    let name = warningData.name;
    let time = warningData.createTime;
    let val = warningData.value;
    let devName = warningData.devName;
    let deviceType = warningData.deviceType;
    let addressType = warningData.addressType;


    if (addressType) {
        var _vectorData = map.getSource('polygons')._data;
        var vectorFeatures = _vectorData.features;
        for (var _index = 0; _index < vectorFeatures.length; _index++) {
            var feature = vectorFeatures[_index];
            var id = feature.properties.id;

            var geometryType = feature.geometry.type;

            if (id && id == addressType && geometryType == 'Polygon') {
                // feature.properties.color = '#DC143C';
                feature.properties.warning = '1';
            }
        }


    }



    map.getSource('polygons').setData(_vectorData);


    var _pointData = map.getSource('points')._data;

    var pointFeatures = _pointData.features;
    for (var _index = 0; _index < pointFeatures.length; _index++) {
        var feature = pointFeatures[_index];
        var id = feature.properties.id;

        var geometryType = feature.geometry.type;


        if (id && id == addressType && geometryType == 'Point') {

            // feature.properties.warning = '1';

            var elMarker = createLocationMarkerElement();


            var marker = new mapboxgl.Marker(elMarker);
            marker.setLngLat(feature.geometry.coordinates);

            marker.setOffset([0, -20]);
            // var html = "车间名称:" + feature.properties.name + '<br />' +
            // 	"报警类型:" + deviceType + '<br />' +
            // 	"报警信息:" + devName + '<br />';

            // marker.setPopup(
            // 	new mapboxgl.Popup({ offset: 25 }) // add popups
            // 		.setHTML(
            // 			html
            // 		)
            // );

            marker.addTo(map);
            currentMarkers.push(marker);
            // marker.togglePopup();
        }



    }

    // map.getSource('points').setData(_pointData);
}


function clearWarningData() {
    if (!mapload) {
        return;
    }

    var _vectorData = map.getSource('polygons')._data;
    var vectorFeatures = _vectorData.features;
    for (var _index = 0; _index < vectorFeatures.length; _index++) {
        var feature = vectorFeatures[_index];
        var id = feature.properties.id;

        var geometryType = feature.geometry.type;

        if (geometryType == 'Polygon') {
            feature.properties.warning = '0';
        }
    }
    map.getSource('polygons').setData(_vectorData);

    //删除marker
    if (currentMarkers) {
        for (var i = currentMarkers.length - 1; i >= 0; i--) {
            currentMarkers[i].remove();
        }
    }
}
function createLocationMarkerElement(title) {
    var elMarker = document.createElement('div');
    elMarker.className = "location-marker";

    var elMarkerIcon = document.createElement('div');
    elMarkerIcon.className = "location-marker-icon"

    var elMarkerIconImage = document.createElement('img');

    elMarkerIconImage.src = 'images/alarm.png';

    elMarkerIcon.appendChild(elMarkerIconImage);

    elMarker.appendChild(elMarkerIcon);

    // var elMarkerLabel = document.createElement('div');
    // elMarkerLabel.className = "location-marker-label";
    // elMarkerLabel.innerText = title;
    // elMarker.appendChild(elMarkerLabel);
    return elMarker;
}


